﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Mvc;
using MovieAPI.Models;
using Newtonsoft.Json.Linq;

namespace MovieAPI.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*"), RequireHttpsAttribute]
    public class ScheduleController : ApiController
    {
        private filmEntities db = new filmEntities();
        [System.Web.Http.HttpGet]
        public IHttpActionResult GetSche(int MovieID)
        {
            var Sche = db.Schedule.Where(S =>S.MovieID == MovieID && S.StartTime > System.DateTime.Now).OrderBy(S => S.StartTime).GroupBy(S => S.StartTime.Month + "月" + S.StartTime.Day + "日").Select(S => new { date = S.Key });
           return Ok(Sche);
        }
        [System.Web.Http.HttpPost]
        public IHttpActionResult GetScheByID([FromBody] dynamic data)
        {
            JObject obj = JObject.Parse(data.ToString());
            var schID = obj["data"]["Orders"].Value<JArray>();
            List<int> ID = new List<int>();
            foreach (var item in schID)
            {
                JObject j = JObject.Parse(item.ToString());
                ID.Add(j["ScheduleID"].Value<int>());
            }
            List<Schedule> schedules = new List<Schedule>();
            foreach (var item in ID)
            {
                schedules.Add(db.Schedule.Where(s => s.ScheduleID == item).FirstOrDefault());
            }
            return Ok(schedules);
        }
        [System.Web.Http.HttpPost]
        public IHttpActionResult GetScheByDate([FromBody] dynamic data)
        {
            JObject obj = JObject.Parse(data.ToString());
            string Schdate = obj["data"]["Schedate"].Value<string>();
            int MovieID =  obj["data"]["MovieID"].Value<int>();
            return Ok(db.Schedule.Where(S => S.StartTime.Month + "月" + S.StartTime.Day + "日"==Schdate && S.MovieID==MovieID && S.StartTime>System.DateTime.Now).Select(S=>new {
                HallType=S.Hall.HallName+"("+S.Hall.HallType+")",ScheInfo=S
            }));
           
        }
        public IHttpActionResult UpDateScheSeat(dynamic data)
        {
            using (filmEntities db=new filmEntities())
            {
                int id = data.data.id;
               Schedule schedule= db.Schedule.Where(S => S.ScheduleID == id).FirstOrDefault();
                schedule.SeatSell = data.data.Seat;
                db.SaveChanges();
                return Ok(200);
            }
        }
        public IHttpActionResult GetHallByScheID(int id)
        {

            var hall = db.Schedule.Where(H => H.ScheduleID == id).Select(H => H.SeatSell).FirstOrDefault();
            string[] HallRow = hall.Split('=');
            string[] StringHallCol = HallRow[0].Split(','); //string[,]是等长数组，列维度一样，只要取任意一行的列维度即可确定整个二维数组的列维度
            int[] IntHallCol = Array.ConvertAll<string, int>(StringHallCol, delegate (string s) { return int.Parse(s); });
            int x = HallRow.Length;
            int y = StringHallCol.Length;
            int[,] twoArray = new int[x, y];
            for (int i = 0; i < x; i++)
            {
                StringHallCol = HallRow[i].Split(',');
                IntHallCol = Array.ConvertAll<string, int>(StringHallCol, delegate (string s) { return int.Parse(s); });
                for (int j = 0; j < IntHallCol.Length; j++)
                {
                    twoArray[i, j] = IntHallCol[j];
                }
            }
            dynamic HallArray = new
            {
                twoArray,
                x,
                y
            };


            //return Ok(db.Hall.Where(H => H.HallID == id).Select(H=>new {Row=H.HallSeat.Length,Col=H.HallSeat[0] }));
            return Ok(HallArray);
        }
        [System.Web.Http.HttpGet]
        public IHttpActionResult GetScheduleAndMovie()
        {
            using (filmEntities db = new filmEntities())
            {
                //查询排片信息
                var schedules = db.Schedule.ToList();
                //查询电影名字
                var MID = schedules.Select(s => s.MovieID);
                List<MovieInfo> movieInfos = new List<MovieInfo>();
                foreach (var item in MID)
                {
                    movieInfos.Add(db.MovieInfo.Where(m => m.MovieID == item).FirstOrDefault());
                }
                //查询影厅名字
                var HID = schedules.Select(s => s.HallID);
                List<Hall> halls = new List<Hall>();
                foreach (var item in HID)
                {
                    halls.Add(db.Hall.Where(h=>h.HallID==item).FirstOrDefault());
                }

                var scheduless = new List<Tuple<string, string, decimal, DateTime, DateTime,int>>();
                for (int i = 0; i < schedules.Count(); i++)
                {
                    scheduless.Add(new Tuple<string, string, decimal, DateTime, DateTime,int>(movieInfos[i].MovieName,halls[i].HallName,schedules[i].Price,schedules[i].StartTime,schedules[i].overTime,schedules[i].ScheduleID));
                }
                return Ok(scheduless);
            }
        }
        [System.Web.Http.HttpPost]
        public IHttpActionResult AddSchedule([FromBody] dynamic data) {
            using (filmEntities db = new filmEntities())
            {
                JObject obj = JObject.Parse(data.ToString());
                int MovieID = obj["data"]["MovieID"].Value<int>();
                int HallID = obj["data"]["HallID"].Value<int>();
                decimal Price = obj["data"]["Price"].Value<decimal>();
                DateTime StartTime = obj["data"]["StartTime"].Value<DateTime>();
                var sch = db.Schedule.Where(s => s.HallID == HallID).ToList();
                var movieTime = db.MovieInfo.Where(M => M.MovieID == MovieID).Select(M => M.MovieDate).ToList().FirstOrDefault();
                foreach (var item in sch)
                {
                    if (item.StartTime <= StartTime && StartTime <= item.overTime)
                    {
                        //返回1为同影厅时间相同，不可排片
                        return Ok(1);
                    }
                }
                if (movieTime>StartTime)
                {
                    return Ok(4);
                }
                else if(StartTime<DateTime.Now)
                {
                    return Ok(5);
                }
                //算出结束时间
                var MoTime = db.MovieInfo.Where(m => m.MovieID == MovieID).Select(a=>a.MovieTime).FirstOrDefault();
                DateTime OverTime = StartTime.AddMinutes(MoTime);
                //获取座位信息
                var HallSeat = db.Hall.Where(c => c.HallID == HallID).Select(b => b.HallSeat).FirstOrDefault();
                //实例化一个排片
                Schedule schedules = new Schedule();
                //将各个数据加入进去
                schedules.HallID = HallID;
                schedules.MovieID = MovieID;
                schedules.overTime = OverTime;
                schedules.Price = Price;
                schedules.SeatSell = HallSeat;
                schedules.StartTime = StartTime;
                db.Schedule.Add(schedules);
                if (db.SaveChanges() > 0)
                {
                    //返回2表示添加成功
                    return Ok(2);
                }
                else {
                    //返回3表示添加失败
                    return Ok(3);
                }
                
            }
        }
        [System.Web.Http.HttpPost]
        public IHttpActionResult UpdataSch([FromBody] dynamic data) 
        {
            using (filmEntities db = new filmEntities())
            {
                JObject obj = JObject.Parse(data.ToString());
                int SchID = obj["data"]["ScheduleID"].Value<int>();
                var Seat = db.Schedule.Where(s => s.ScheduleID == SchID).Select(a => a.SeatSell).FirstOrDefault();
                int MovieID = obj["data"]["MovieID"].Value<int>();
                int HallID = obj["data"]["HallID"].Value<int>();
                decimal Price = obj["data"]["Price"].Value<decimal>();
                DateTime StartTime = obj["data"]["StartTime"].Value<DateTime>();
                var sch = db.Schedule.Where(s => s.HallID == HallID).ToList();
                foreach (var item in sch)
                {
                    if (item.StartTime <= StartTime && StartTime <= item.overTime)
                    {
                        //返回1为同影厅时间相同，不可排片
                        return Ok(1);
                    }
                }
                var MoTime = db.MovieInfo.Where(m => m.MovieID == MovieID).Select(a => a.MovieTime).FirstOrDefault();
                DateTime OverTime = StartTime.AddMinutes(MoTime);
                Schedule schedules = new Schedule();
                //将各个数据加入进去
                schedules.ScheduleID = SchID;
                schedules.HallID = HallID;
                schedules.MovieID = MovieID;
                schedules.overTime = OverTime;
                schedules.Price = Price;
                schedules.SeatSell = Seat;
                schedules.StartTime = StartTime;
                db.Entry(schedules).State = EntityState.Modified;
                if (db.SaveChanges()>0)
                {
                    return Ok(2);
                }
                else
                {
                    return Ok(3);
                }
                
            }
            

        }
    }
}
